import axios from "axios";
import { Message } from "element-ui";
import NProgress from "nprogress";//引入进度条 
import 'nprogress/nprogress.css';//进度条css 不然进度条不显示
import { DefaultUrl } from "./DefaultUrl";//保存基础地址的页面
import { getToken } from "./TokenTools";
import { removeToken } from "@/utils/TokenTools";
import { Loading } from 'element-ui';//引入加载
import router from '../router';
const instance = axios.create({
    timeout: 5000, // 请求超时时间
    baseURL: DefaultUrl, // 请求的基础地址
    //withCredentials: true,//跨域使用 且需要后端配合 这样就可以设置cookie
    headers: {        // cookie: '123456',
        token: getToken(),//增加token
    }

});
let Notify = Message;


let loadingInstance;
// 继续封装一个请求和相应拦截
// 比如有些服务器接口在请求之前需要添加全局统一的配置信息
//  我们需要对网络请求的异常做统一捕获
// Add a request interceptor
//  全局请求拦截，在发起请求之前触发
//    1. 添加全局loading
//    1. 在请求头添加token
instance.interceptors.request.use(
    function (config) {
        NProgress.start();//进度条开始 假的进度条
        loadingInstance = Loading.service({ target: ".content", text: "加载中别慌..." });//整页覆盖的加载
        // Do something before request is sent
        // config.headers["cooAccess-Control-Allow-Credentialskie"] = true;
        if (!config.headers.token) {
            config.headers.token = getToken();//增加token 未知原因导致token传递失败时 在此判断传递token
        }
        return config;
    },
    function (error) {
        // Do something with request error
        return Promise.reject(error);
    }
);

// Add a response interceptor
// 全局相应拦截，网络请求返回之后触发，可以做错误处理
//  1. 清除loading
//  2. 错误异常处理
instance.interceptors.response.use(
    function (response) {
        NProgress.done();//进度条消失
        loadingInstance.close();//加载消失
        // Any status code that lie within the range of 2xx cause this function to trigger
        // Do something with response data
        return response.data;//直接返回data数据
    },
    function (error) {
        NProgress.done();
        loadingInstance.close();//加载消失
        //console.dir(error);
        if (error.message && error.message.indexOf("timeout") > -1) {
            Notify({
                type: "danger",
                message: "网络不稳定，请刷新重试",
            });
        } else if (error.message && error.message.indexOf("Network Error") > -1) {
            Notify({
                type: "danger",
                message: "网络错误,网络已断开",
            });
        } else {
            let a = "" + error;
            if (a.indexOf('code 401') > -1) {
                console.log(a);
                Message.error('用户登录失效');
                removeToken();
                router.replace({ name: "Login" });
            } else {
                Notify({
                    type: "danger",
                    message: "未知错误,请重试",
                });
            }

        }


        console.log(1);
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error

        return Promise.reject(error);
    }
);

/**
 * 发起get请求
 * @param {*} url
 * @param {*} params
 */
export const get = (url, params) => instance.get(url, { params });

// export function get(url, params) {
//   return instance.get(url, { params })
// }

/**
 * 发起post请求
 * @param {*} url
 * @param {*} data
 */
export const post = (url, data) => instance.post(url, data);

/**
 * put请求
 * @param {*} url
 * @param {*} data
 */
export const put = (url, data) => instance.put(url, data);

/**
 * delete请求
 * @param {*} url
 */
export const del = (url) => instance.delete(url);
